# 退费任务管理系统 Nginx 部署脚本
# 支持企业微信H5应用访问和生产环境部署
# 作者: AI Assistant
# 版本: 2.0
# 更新时间: 2024-01-20

param(
    [string]$NginxPath = "C:\nginx",
    [string]$Domain = "www.lzetyy.com",
    [int]$Port = 443,
    [string]$AccessPath = "/refundtask/",
    [string]$BackendAPI = "https://www.lzetyy.com:6724/api/",
    [string]$DeployMode = "production", # development, production, dmz
    [string]$ProductionServer = "www.lzetyy.com", # 生产服务器地址
    [string]$SSLCertPath = "cert/server.crt",
    [string]$SSLKeyPath = "cert/server.key"
)

# 颜色输出函数
function Write-Success { param([string]$Message) Write-Host $Message -ForegroundColor Green }
function Write-Warning-Custom { param([string]$Message) Write-Host $Message -ForegroundColor Yellow }
function Write-Error-Custom { param([string]$Message) Write-Host $Message -ForegroundColor Red }
function Write-Info { param([string]$Message) Write-Host $Message -ForegroundColor Cyan }

try {
    Write-Info "========================================"
    Write-Info "🚀 退费任务管理系统 - Nginx子路径部署"
    Write-Info "========================================"
    Write-Host ""
    
    # 显示配置信息
    Write-Info "📋 部署配置信息："
    Write-Host "   部署模式: $DeployMode" -ForegroundColor White
    Write-Host "   域名: $Domain" -ForegroundColor White
    Write-Host "   端口: $Port" -ForegroundColor White
    Write-Host "   访问路径: https://$Domain$AccessPath" -ForegroundColor White
    Write-Host "   后端API: $BackendAPI" -ForegroundColor White
    Write-Host "   Nginx路径: $NginxPath" -ForegroundColor White
    if ($DeployMode -eq "production" -or $DeployMode -eq "dmz") {
        Write-Host "   SSL证书: $SSLCertPath" -ForegroundColor White
        Write-Host "   SSL私钥: $SSLKeyPath" -ForegroundColor White
    }
    Write-Host ""
    
    # 检查Node.js和npm
    Write-Info "🔍 检查环境依赖..."
    try {
        $nodeVersion = node --version
        Write-Success "✅ Node.js: $nodeVersion"
    } catch {
        Write-Error-Custom "❌ Node.js 未安装或不在PATH中"
        throw "请先安装 Node.js"
    }
    
    try {
        $npmVersion = npm --version
        Write-Success "✅ npm: $npmVersion"
    } catch {
        Write-Error-Custom "❌ npm 未安装或不在PATH中"
        throw "请先安装 npm"
    }
    
    # 检查项目依赖
    Write-Info "📦 检查项目依赖..."
    if (!(Test-Path "node_modules")) {
        Write-Warning-Custom "⚠️  node_modules 不存在，正在安装依赖..."
        npm install
        if ($LASTEXITCODE -ne 0) {
            throw "npm install 失败"
        }
        Write-Success "✅ 依赖安装完成"
    } else {
        Write-Success "✅ 项目依赖已存在"
    }
    
    # 构建项目
    Write-Info "🔨 构建生产版本..."
    npm run build
    if ($LASTEXITCODE -ne 0) {
        throw "构建失败"
    }
    Write-Success "✅ 项目构建完成"
    
    # 检查构建结果
    $distPath = Join-Path $PWD "dist"
    if (!(Test-Path $distPath)) {
        throw "构建目录不存在: $distPath"
    }
    
    $indexPath = Join-Path $distPath "index.html"
    if (!(Test-Path $indexPath)) {
        throw "index.html 文件不存在"
    }
    
    Write-Success "✅ 构建文件验证通过"
    
    # 生成nginx配置文件
    Write-Info "📝 生成Nginx配置文件..."
    
    # 根据部署模式生成不同的配置
    if ($DeployMode -eq "dmz") {
        # DMZ区域配置 - 添加到现有server块中的location配置
        $nginxConfigContent = @"
# 退费任务管理系统配置片段
# 请将以下配置添加到现有的 server { listen 8443 ssl; } 块中

##退费任务管理系统
location $AccessPath {
    # 静态文件服务
    alias /var/local/nginx/html/refundtask/;
    try_files `$uri `$uri/ $AccessPath/index.html;
    index index.html index.htm;
    
    # 安全头设置
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    
    # 企业微信H5应用支持
    add_header Access-Control-Allow-Origin "*";
    add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
    add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range";
}

# API代理配置 - 转发到后端服务器
location $AccessPath/api/ {
    proxy_pass $BackendAPI;
    proxy_set_header Host `$host;
    proxy_set_header X-Real-IP `$remote_addr;
    proxy_set_header X-Forwarded-For `$proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto `$scheme;
    
    # 超时设置
    proxy_connect_timeout 30s;
    proxy_send_timeout 30s;
    proxy_read_timeout 30s;
    
    # 缓冲设置
    proxy_buffering on;
    proxy_buffer_size 4k;
    proxy_buffers 8 4k;
    
    # CORS设置
    add_header Access-Control-Allow-Origin "*" always;
    add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
    add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization" always;
    
    # 处理预检请求
    if (`$request_method = 'OPTIONS') {
        add_header Access-Control-Allow-Origin "*";
        add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
        add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization";
        add_header Access-Control-Max-Age 1728000;
        add_header Content-Type "text/plain; charset=utf-8";
        add_header Content-Length 0;
        return 204;
    }
}

# 静态资源缓存配置
location ~* $AccessPath.*\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|wasm)`$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
    add_header Access-Control-Allow-Origin "*";
}
"@
    } elseif ($DeployMode -eq "production") {
        # 生产环境独立server配置
        $nginxConfigContent = @"
# Nginx配置文件 - 退费审核管理系统移动端（生产环境）
# 生成时间: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')

worker_processes auto;
error_log logs/error.log;
pid logs/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    # 退费任务管理系统 - 生产环境
    server {
        listen $Port ssl http2;
        server_name $Domain;
        
        # SSL证书配置
        ssl_certificate $SSLCertPath;
        ssl_certificate_key $SSLKeyPath;
        ssl_session_timeout 5m;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_prefer_server_ciphers on;
        
        # 网站根目录
        root $($distPath.Replace('\', '/'));
        index index.html index.htm;
        
        # 字符编码
        charset utf-8;
        
        # 日志配置
        access_log logs/refund_task_access.log;
        error_log logs/refund_task_error.log;
        
        # Gzip压缩配置
        gzip on;
        gzip_vary on;
        gzip_min_length 1024;
        gzip_comp_level 6;
        gzip_types
            text/plain
            text/css
            text/xml
            text/javascript
            application/javascript
            application/xml+rss
            application/json
            application/wasm;
        
        # 主要路由配置
        location / {
            try_files `$uri `$uri/ /index.html;
            
            # 安全头设置
            add_header X-Frame-Options "SAMEORIGIN" always;
            add_header X-Content-Type-Options "nosniff" always;
            add_header X-XSS-Protection "1; mode=block" always;
            add_header Referrer-Policy "strict-origin-when-cross-origin" always;
            
            # 企业微信H5应用支持
            add_header Access-Control-Allow-Origin "*";
            add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
            add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range";
        }
        
        # API代理配置
        location /api/ {
            proxy_pass $BackendAPI;
            proxy_set_header Host `$host;
            proxy_set_header X-Real-IP `$remote_addr;
            proxy_set_header X-Forwarded-For `$proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto `$scheme;
            
            # 超时设置
            proxy_connect_timeout 30s;
            proxy_send_timeout 30s;
            proxy_read_timeout 30s;
            
            # CORS设置
            add_header Access-Control-Allow-Origin "*" always;
            add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
            add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization" always;
            
            # 处理预检请求
            if (`$request_method = 'OPTIONS') {
                add_header Access-Control-Allow-Origin "*";
                add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
                add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization";
                add_header Access-Control-Max-Age 1728000;
                add_header Content-Type "text/plain; charset=utf-8";
                add_header Content-Length 0;
                return 204;
            }
        }
        
        # 静态资源缓存配置
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|wasm)`$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
            add_header Access-Control-Allow-Origin "*";
        }
    }
}
"@
    } else {
        # 开发环境配置
        $nginxConfigContent = @"
# Nginx配置文件 - 退费审核管理系统移动端
# 支持子路径 $AccessPath 访问
# 生成时间: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')

# 全局配置
worker_processes auto;
error_log logs/error.log;
pid logs/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    # 服务器配置
    server {
        listen $Port ssl http2;
        listen 80;
        server_name $Domain;
        
        # SSL证书配置（请根据实际情况修改）
        # ssl_certificate /path/to/your/certificate.crt;
        # ssl_certificate_key /path/to/your/private.key;
        # ssl_protocols TLSv1.2 TLSv1.3;
        # ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
        
        # 网站根目录
        root $($distPath.Replace('\', '/'));
        index index.html index.htm;
        
        # 字符编码
        charset utf-8;
        
        # 日志配置
        access_log logs/refund_task_access.log;
        error_log logs/refund_task_error.log;
        
        # Gzip压缩配置
        gzip on;
        gzip_vary on;
        gzip_min_length 1024;
        gzip_comp_level 6;
        gzip_types
            text/plain
            text/css
            text/xml
            text/javascript
            application/javascript
            application/xml+rss
            application/json
            application/wasm;
        
        # 主要路由配置 - 支持 $AccessPath 子路径
        location $AccessPath {
            alias $($distPath.Replace('\', '/'));
            try_files `$uri `$uri/ $AccessPath/index.html;
            index index.html index.htm;
            
            # 安全头设置
            add_header X-Frame-Options "SAMEORIGIN" always;
            add_header X-Content-Type-Options "nosniff" always;
            add_header X-XSS-Protection "1; mode=block" always;
            add_header Referrer-Policy "strict-origin-when-cross-origin" always;
            
            # 企业微信H5应用支持
            add_header Access-Control-Allow-Origin "*";
            add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
            add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range";
        }
        
        # API代理配置 - 转发到后端服务器
        location $AccessPath/api/ {
            proxy_pass $BackendAPI;
            proxy_set_header Host `$host;
            proxy_set_header X-Real-IP `$remote_addr;
            proxy_set_header X-Forwarded-For `$proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto `$scheme;
            
            # 超时设置
            proxy_connect_timeout 30s;
            proxy_send_timeout 30s;
            proxy_read_timeout 30s;
            
            # 缓冲设置
            proxy_buffering on;
            proxy_buffer_size 4k;
            proxy_buffers 8 4k;
            
            # CORS设置
            add_header Access-Control-Allow-Origin "*" always;
            add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
            add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization" always;
            
            # 处理预检请求
            if (`$request_method = 'OPTIONS') {
                add_header Access-Control-Allow-Origin "*";
                add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
                add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization";
                add_header Access-Control-Max-Age 1728000;
                add_header Content-Type "text/plain; charset=utf-8";
                add_header Content-Length 0;
                return 204;
            }
        }
        
        # 静态资源缓存配置
        location ~* $AccessPath.*\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|wasm)`$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
            add_header Vary "Accept-Encoding";
            
            # 跨域设置
            add_header Access-Control-Allow-Origin "*";
        }
        
        # HTML文件缓存配置
        location ~* $AccessPath.*\.html`$ {
            expires 1h;
            add_header Cache-Control "public, must-revalidate";
        }
        
        # 根路径重定向到 $AccessPath
        location = / {
            return 301 $AccessPath;
        }
        
        # 禁止访问敏感文件
        location ~ /\. {
            deny all;
            access_log off;
            log_not_found off;
        }
        
        location ~ ~`$ {
            deny all;
            access_log off;
            log_not_found off;
        }
        
        # 错误页面配置
        error_page 404 $AccessPath/index.html;
        error_page 500 502 503 504 /50x.html;
        
        location = /50x.html {
            root html;
        }
    }
    
    # HTTP到HTTPS重定向
    server {
        listen 80;
        server_name $Domain;
        return 301 https://`$server_name`$request_uri;
    }
}
"@
    }
    
    $nginxConfigPath = Join-Path $PWD "nginx-refundtask-generated.conf"
    $nginxConfigContent | Out-File -FilePath $nginxConfigPath -Encoding UTF8
    Write-Success "✅ Nginx配置文件已生成: $nginxConfigPath"
    
    # 根据部署模式显示不同的部署说明
    Write-Info "📋 部署说明:"
    if ($DeployMode -eq "dmz") {
        Write-Info "🌐 DMZ区域部署模式:"
        Write-Info "1. 将 $distPath 目录复制到DMZ服务器的 /var/local/nginx/html/refundtask/"
        Write-Info "2. 将生成的配置片段添加到现有的 server { listen 8443 ssl; } 块中"
        Write-Info "3. 确保后端API服务 $BackendAPI 可访问"
        Write-Info "4. 重新加载 Nginx 配置: nginx -s reload"
        Write-Info "5. 访问地址: https://$Domain:8443$AccessPath"
        Write-Warning "⚠️  注意: 这是配置片段，需要手动添加到现有的nginx配置中"
    } elseif ($DeployMode -eq "production") {
        Write-Info "🏭 生产环境独立部署模式:"
        Write-Info "1. 将 $distPath 目录复制到生产服务器"
        Write-Info "2. 确保SSL证书文件存在: $SSLCertPath 和 $SSLKeyPath"
        Write-Info "3. 将生成的完整nginx配置文件部署到服务器"
        Write-Info "4. 确保后端API服务 $BackendAPI 可访问"
        Write-Info "5. 重新加载 Nginx 配置: nginx -s reload"
        Write-Info "6. 访问地址: https://$Domain:$Port/"
    } else {
        Write-Info "🔧 开发环境部署模式:"
        Write-Info "1. 将 $distPath 目录复制到服务器的 /var/local/nginx/html/refundtask/"
        Write-Info "2. 将生成的 nginx-refundtask-generated.conf 配置添加到 Nginx 主配置文件中"
        Write-Info "3. 配置SSL证书（如需要）"
        Write-Info "4. 重新加载 Nginx 配置: nginx -s reload"
        Write-Info "5. 访问地址: https://$Domain:$Port$AccessPath"
    }
    
    Write-Info ""
    Write-Info "📁 相关文件:"
    Write-Info "- 前端构建文件: $distPath"
    Write-Info "- Nginx配置文件: $nginxConfigPath"
    if ($DeployMode -eq "production") {
        Write-Info "- SSL证书文件: $SSLCertPath"
        Write-Info "- SSL私钥文件: $SSLKeyPath"
    }
    Write-Info "- 后端API地址: $BackendAPI"
    
    # 生成部署说明
    $deployGuideContent = @"
# 退费任务管理系统 - 子路径部署说明

## 部署信息
- **生成时间**: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
- **域名**: $Domain
- **访问地址**: https://$Domain/refundtask/
- **登录地址**: https://$Domain/refundtask/login
- **后端API**: $BackendAPI
- **构建目录**: $distPath

## 部署步骤

### 1. 安装Nginx
如果尚未安装Nginx，请：
1. 下载Nginx: http://nginx.org/en/download.html
2. 解压到: $NginxPath

### 2. 配置SSL证书（HTTPS）
1. 获取SSL证书文件（.crt和.key）
2. 将证书文件放置在安全目录
3. 修改nginx配置文件中的SSL证书路径：
   ```
   ssl_certificate /path/to/your/certificate.crt;
   ssl_certificate_key /path/to/your/private.key;
   ```

### 3. 部署Nginx配置
1. 复制生成的配置文件到Nginx配置目录：
   ```
   copy "$nginxConfigPath" "$NginxPath\conf\nginx.conf"
   ```
2. 或者在主配置文件中include这个配置

### 4. 启动Nginx
```bash
cd $NginxPath
nginx.exe
```

### 5. 验证部署
1. 访问: https://$Domain/refundtask/
2. 测试登录功能
3. 检查API调用是否正常

## 管理命令

### 启动/停止Nginx
```bash
# 启动
cd $NginxPath && nginx.exe

# 停止
nginx -s stop

# 重新加载配置
nginx -s reload

# 测试配置
nginx -t
```

### 查看日志
```bash
# 访问日志
type "$NginxPath\logs\refund_task_access.log"

# 错误日志
type "$NginxPath\logs\refund_task_error.log"
```

## 故障排除

### 1. 页面无法访问
- 检查Nginx是否启动
- 检查端口是否被占用
- 检查防火墙设置

### 2. API调用失败
- 确认后端服务运行在 $BackendUrl
- 检查nginx错误日志
- 验证CORS设置

### 3. SSL证书问题
- 确认证书文件路径正确
- 检查证书是否过期
- 验证证书域名匹配

## 更新部署

当需要更新前端代码时：
1. 重新运行此脚本
2. 或者手动执行：
   ```
   npm run build
   nginx -s reload
   ```

## 注意事项

1. **SSL证书**: 生产环境必须配置有效的SSL证书
2. **防火墙**: 确保端口$Port已开放
3. **域名解析**: 确保域名$Domain正确解析到服务器
4. **后端服务**: 确保后端API服务正常运行
5. **权限**: 确保Nginx有读取构建文件的权限

"@
    
    $deployGuidePath = Join-Path $PWD "部署说明-refundtask.md"
    $deployGuideContent | Out-File -FilePath $deployGuidePath -Encoding UTF8
    Write-Success "✅ 部署说明已生成: $deployGuidePath"
    
    # 显示完成信息
    Write-Info "========================================"
    Write-Success "🎉 部署准备完成！"
    Write-Host ""
    Write-Info "📁 生成的文件："
    Write-Host "   构建目录: $distPath" -ForegroundColor Blue
    Write-Host "   Nginx配置: $nginxConfigPath" -ForegroundColor Blue
    Write-Host "   部署说明: $deployGuidePath" -ForegroundColor Blue
    Write-Host ""
    Write-Info "🚀 接下来的步骤："
    Write-Host "1. 配置SSL证书（修改nginx配置文件中的证书路径）" -ForegroundColor White
    Write-Host "2. 将nginx配置文件复制到Nginx配置目录" -ForegroundColor White
    Write-Host "3. 启动Nginx服务" -ForegroundColor White
    Write-Host "4. 访问 https://$Domain/refundtask/login" -ForegroundColor White
    Write-Host ""
    Write-Info "📖 详细说明请查看: $deployGuidePath"
    Write-Info "========================================"
    Write-Host ""
    
    # 询问用户操作
    $openGuide = Read-Host "是否打开部署说明？(Y/N)"
    if ($openGuide -eq "Y" -or $openGuide -eq "y") {
        if (Test-Path $deployGuidePath) {
            Start-Process $deployGuidePath
        }
    }
    
    $openConfig = Read-Host "是否打开Nginx配置文件？(Y/N)"
    if ($openConfig -eq "Y" -or $openConfig -eq "y") {
        if (Test-Path $nginxConfigPath) {
            Start-Process "notepad.exe" -ArgumentList $nginxConfigPath
        }
    }
    
    $openDist = Read-Host "是否打开构建目录？(Y/N)"
    if ($openDist -eq "Y" -or $openDist -eq "y") {
        if (Test-Path $distPath) {
            Start-Process "explorer.exe" -ArgumentList $distPath
        }
    }
    
} catch {
    Write-Error-Custom "部署过程中发生错误：$($_.Exception.Message)"
    Write-Host $_.ScriptStackTrace -ForegroundColor Red
} finally {
    Write-Host "部署脚本执行完成！" -ForegroundColor Cyan
    Read-Host "按任意键退出"
}